package com.ruoyi.cart.service.impl;

import com.ruoyi.cart.domain.Cart;
import com.ruoyi.cart.domain.CartDetail;
import com.ruoyi.cart.mapper.CartMapper;
import com.ruoyi.cart.service.ICartService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.orderdetails.service.IOrderdetailsService;
import com.ruoyi.product.service.IProductsService;
import com.ruoyi.redis.RedisDistributedLock;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 购物车Service业务层处理（带Redis缓存）
 */
@CacheConfig(cacheNames = "cart")
@Service
public class CartServiceImpl implements ICartService {
    private static final String CART_KEY_PREFIX = "cart:";
    private static final String CART_LIST_KEY_PREFIX = "cart:list:";
    private static final String CART_DETAIL_LIST_KEY_PREFIX = "cart:detail:list:";
    private static final Integer CACHE_EXPIRE_TIME = 30; // 缓存过期时间30分钟

    @Autowired
    private ISysUserService userService;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private IProductsService productsService;

    @Autowired
    private IOrderdetailsService orderdetailsService;

    @Autowired
    private RedisCache redisCache;

    /**
     分布式&&限流
     */
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedisDistributedLock redisLock;

    private static final String STOCK_KEY_PREFIX = "stock:";
    private static final String LOCK_KEY_PREFIX = "lock:stock:";

    /**
     * 查询购物车（带缓存）
     */
    @Override
    @Cacheable(key = "'cart:' + #cartId", unless = "#result == null")
    public Cart selectCartByCartId(Long cartId) {
        return cartMapper.selectCartByCartId(cartId);
    }

    /**
     * 查询购物车列表（带详情，带缓存）
     */
    @Cacheable(key = "'cart:list:' + #cart.cartId", unless = "#result == null")
    public List<CartDetail> selectCartList02(Cart cart) {
        String userName = cart.getUserName();
        String key = CART_DETAIL_LIST_KEY_PREFIX + userName;

        // 先从缓存获取
        List<CartDetail> cachedList = redisCache.getCacheList(key);
        if (cachedList != null && !cachedList.isEmpty()) {
            return cachedList;
        }

        // 缓存没有则查询数据库
        List<Cart> list = cartMapper.selectCartList(cart);
        List<CartDetail> list02 = new ArrayList<>();

        for(Cart list01 : list) {
            CartDetail cartDetail = new CartDetail();
            String productName;
            BigDecimal price;

            if(productsService.selectProductsByProductId(list01.getProductId()) == null) {
                productName = "该商品已下架";
                price = BigDecimal.ZERO;
            } else {
                productName = productsService.selectProductsByProductId(list01.getProductId()).getProductName();
                price = productsService.selectProductsByProductId(list01.getProductId()).getPrice();
            }

            Long quantity = list01.getQuantity();
            cartDetail.setUserName(list01.getUserName());
            BigDecimal quantityBigDecimal = BigDecimal.valueOf(quantity);
            BigDecimal totalAmount = price.multiply(quantityBigDecimal);
            cartDetail.setTotalAmount(totalAmount.toString());
            cartDetail.setProductName(productName);
            cartDetail.setCartId(list01.getCartId());
            cartDetail.setQuantity(quantity);
            cartDetail.setAddedDate(list01.getAddedDate());
            list02.add(cartDetail);
        }

        if (!list02.isEmpty()) {
            // 存入缓存
            redisCache.setCacheList(key, list02);
            redisCache.expire(key, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        }

        return list02;
    }

    /**
     * 查询购物车列表（基础信息，带缓存）
     */
    @Override
    public List<Cart> selectCartList(Cart cart) {
        String userName = cart.getUserName();
        String key = CART_LIST_KEY_PREFIX + userName;

        // 先从缓存获取
        List<Cart> cachedList = redisCache.getCacheList(key);
        if (cachedList != null && !cachedList.isEmpty()) {
            return cachedList;
        }

        // 缓存没有则查询数据库
        List<Cart> list = cartMapper.selectCartList(cart);

        if (list != null && !list.isEmpty()) {
            // 存入缓存
            redisCache.setCacheList(key, list);
            redisCache.expire(key, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        }

        return list;
    }

    /**
     * 新增购物车（同步缓存）
     */
    @Override
    @Cacheable(key = "'cart:' + #cart.cartId", unless = "#result == 0")
    public int insertCart(Cart cart) {
        boolean stockDeducted = productsService.decreaseStock(
                cart.getProductId(),
                cart.getQuantity()
        );
        if (!stockDeducted) {
            throw new RuntimeException("库存不足，无法添加购物车");
        }
        int result = cartMapper.insertCart(cart);
        if (result > 0) {
            // 清除相关的列表缓存
            clearListCache(cart.getUserName());
            // 缓存新创建的购物车项
            String key = CART_KEY_PREFIX + cart.getUserName();
            redisCache.setCacheObject(key, cart, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        }else {
            productsService.increaseStock(cart.getProductId(), cart.getQuantity());
        }
        return result;
    }

    /**
     * 修改购物车（同步缓存）
     */
    @Override
    @Cacheable(key = "'cart:' + #cart.cartId", unless = "#result == 0")
    public int updateCart(Cart cart) {
        int result = cartMapper.updateCart(cart);
        if (result > 0) {
            // 更新单个购物车缓存
            String key = CART_KEY_PREFIX + cart.getUserName();
            redisCache.setCacheObject(key, cart, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
            // 清除相关的列表缓存
            clearListCache(cart.getUserName());
        }
        return result;
    }

    /**
     * 批量删除购物车（同步缓存）
     */
    @Override
    @Cacheable(key = "'cart:' + #cartIds")
    public int deleteCartByCartIds(Long[] cartIds) {
        // 先获取所有要删除的购物车项的用户名
        List<Cart> carts = new ArrayList<>() ;
        Set<String> userNames = new HashSet<>();
        for (Long cartId : cartIds) {
            Cart cart = cartMapper.selectCartByCartId(cartId);
            if (cart != null) {
                userNames.add(cart.getUserName());
            }
        }

        int result = cartMapper.deleteCartByCartIds(cartIds);
        if (result > 0) {
            for (Cart cart : carts){
                productsService.increaseStock(cart.getProductId(), cart.getQuantity());
            }
            // 清除相关用户的列表缓存
            for (String userName : userNames) {
                clearListCache(userName);
            }
        }
        return result;
    }

    /**
     * 删除购物车（同步缓存）
     */
    @Override
    @Cacheable(key = "'cart:' + #cartId")
    public int deleteCartByCartId(Long cartId) {
        // 先查询购物车获取userName
        Cart cart = cartMapper.selectCartByCartId(cartId);
        int result = cartMapper.deleteCartByCartId(cartId);
        if (result > 0 && cart != null) {
            // 清除相关的列表缓存
            clearListCache(cart.getUserName());
            productsService.increaseStock(cart.getProductId(), cart.getQuantity());
        }
        return result;
    }

    /**
     * 清除用户相关的购物车列表缓存
     */
    private void clearListCache(String userName) {
        // 清除普通列表缓存

        redisCache.deleteObject(CART_KEY_PREFIX + userName);
        redisCache.deleteObject(CART_LIST_KEY_PREFIX + userName);
        // 清除带详情的列表缓存
        redisCache.deleteObject(CART_DETAIL_LIST_KEY_PREFIX + userName);
    }
}